package org.os.framework.crypto.engine;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;

import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.os.framework.crypto.model.Generator;
import org.os.framework.crypto.model.Keypair;

import lombok.SneakyThrows;

/**
 * SM2密钥生成器
 * 
 * @author
 */
public class Sm2Generator implements Generator {

    private static final String EC_GEN_PARAMETER_SPEC = "sm2p256v1";
    private static final String ALGORITHM = "EC";

    @SneakyThrows
    @Override
    public Keypair generate() {
        final ECGenParameterSpec parameterSpec = new ECGenParameterSpec(EC_GEN_PARAMETER_SPEC);
        final KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM, new BouncyCastleProvider());
        generator.initialize(parameterSpec, new SecureRandom());
        KeyPair keyPair = generator.generateKeyPair();
        BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
        BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();
        byte[] privateBytes = privateKey.getD().toByteArray();
        byte[] publicBytes = publicKey.getQ().getEncoded(false);
        return Keypair.builder()
                .privateKey(Hex.toHexString(privateBytes, privateBytes.length - 32, 32))
                .publicKey(Hex.toHexString(publicBytes))
                .build();
    }

}
